package org.sean.framework.web.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.resource.ResourceHttpRequestHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 判断是否为 自定义的API, 用于统一处理后续操作
 *
 * @author xielei
 */
public class ApiInterceptor implements HandlerInterceptor {

    private static final ThreadLocal<Boolean> API_EXECUTED = new ThreadLocal<>();

    /**
     * @return 是否执行过
     */
    public static boolean isExecuted() {
        return API_EXECUTED.get() != null && API_EXECUTED.get();
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        if (!(handler instanceof ResourceHttpRequestHandler)) {
            API_EXECUTED.set(true);
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
        // do nothing
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        API_EXECUTED.remove();
    }
}
